<template>
  <div class="task_det">
    <navigate
      >查看答卷结果
      <template v-slot:right>
        <div class="red_dot" v-if="false"></div>
        <img
          @click="toDelete"
          class="del_img"
          src="@/assets/images/userRecord/delete.png"
          alt=""
        />
      </template>
    </navigate>
    <div class="block_item bottom_padding_1389">
      <div class="scale_topic bottom_line">
        <div class="scale_name">{{ info.paper_name }}</div>
        <div class="scale_tip">本次问卷得分：{{ info.total_score }}分</div>
      </div>
      <div class="inner_title padding_aside_694 margin_1">
        <img class="deraction_img" src="@/assets/images/common/bar.png" alt />
        <div>用户基本情况</div>
      </div>
      <div class="user_info">
        <div class="info_item width_6 info_label border_right border_bottom">
          测评用户
        </div>
        <div class="info_item width_8 info_ctt border_right border_bottom">
          {{ info.user_name }}
        </div>
        <div class="info_item width_3 info_label border_right border_bottom">
          年龄
        </div>
        <div class="info_item width_4 info_ctt border_bottom">
          {{ info.age }}
        </div>
        <div class="info_item width_6 info_label border_right border_bottom">
          用户联系电话
        </div>
        <div class="info_item width_8 info_ctt border_right border_bottom">
          {{ info.phone }}
        </div>
        <div class="info_item width_3 info_label border_right border_bottom">
          性别
        </div>
        <div class="info_item width_4 info_ctt border_bottom">
          {{ info.sex == 1 ? "男" : "女" }}
        </div>
        <div class="info_item width_6 info_label border_right border_bottom">
          注册账号
        </div>
        <div class="info_item width_8 info_ctt border_right border_bottom">
          {{ info.username }}
        </div>
        <div class="info_item width_3 info_label border_right border_bottom">
          编号
        </div>
        <div class="info_item width_4 info_ctt border_bottom">
          {{ info.id }}
        </div>
        <div class="info_item width_6 info_label border_right border_bottom">
          账号类型
        </div>
        <div class="info_item width_8 info_ctt border_right border_bottom">
          {{ info.role_name }}
        </div>
        <div class="info_item width_3 info_label border_right border_bottom">
          状态
        </div>
        <div class="info_item width_4 info_ctt border_bottom">
          {{ getStudentStatus(info.student_status) }}
        </div>

        <div class="info_item width_6 info_label border_right border_bottom">
          所在单位
        </div>
        <div class="info_item width_7 info_ctt border_bottom">
          {{ info.unit_name }}
        </div>
        <div class="info_item width_6 info_label border_right border_bottom">
          所在部门
        </div>
        <div class="info_item width_8 info_ctt border_right border_bottom">
          {{ info.department_name }}
        </div>
        <div class="info_item width_3 info_label border_right border_bottom">
          管理员
        </div>
        <div class="info_item width_4 info_ctt border_bottom">--</div>
        <div class="info_item width_6 info_label border_right border_bottom">
          问卷所属分类
        </div>
        <div class="info_item width_8 info_ctt border_right border_bottom">
          {{ info.paper_type_name }}
        </div>
        <div class="info_item width_3 info_label border_right border_bottom">
          满分值
        </div>
        <div class="info_item width_4 info_ctt border_bottom">
          {{ info.paper_total_score }}
        </div>
        <div class="info_item width_6 info_label border_right border_bottom">
          答题最长限时
        </div>
        <div class="info_item width_8 info_ctt border_right border_bottom">
          {{ info.paper_time_limited }}
        </div>
        <div class="info_item width_3 info_label border_right border_bottom">
          题目数
        </div>
        <div class="info_item width_4 info_ctt border_bottom">
          {{ info.paper_topic_num }}
        </div>
        <div class="info_item width_6 info_label border_right border_bottom">
          我的交卷时间
        </div>
        <div class="info_item width_7 info_ctt border_bottom">
          {{ convertTimestampToDateTime(info.time) }}
        </div>
        <div class="info_item width_6 info_label border_right">
          我的答卷用时
        </div>
        <div class="info_item width_8 info_ctt border_right">
          {{ info.finish_used_time }}
        </div>
        <div class="info_item width_3 info_label border_right">结果点评</div>
        <div class="info_item width_4 info_ctt">
          {{ info.is_comment == 1 ? "已点评" : "未点评" }}
        </div>
      </div>
    </div>

    <div class="inner_title padding_aside_694 margin_1">
      <img class="deraction_img" src="@/assets/images/common/bar.png" alt />
      <div>问卷答题结果</div>
    </div>
    <div class="block_item pad_0_14">
      <!-- 动态渲染题目 -->
      <div
        class="question_box"
        v-for="(paperTopic, index) in info.paperTopic || []"
        :key="paperTopic.id"
      >
        <div class="type_tit">
          {{ index + 1 }}.【{{
            getQuestionTypeName(paperTopic.topic.type)
          }}】({{ paperTopic.topic.score }}分)
        </div>
        <div class="question_tit" v-html="paperTopic.topic.content"></div>

        <!-- 根据题目类型渲染不同的答案区域 -->
        <div class="answer_area">
          <!-- 单选题 -->
          <div
            v-if="paperTopic.topic.type === 1"
            class="answer_item"
            v-for="answer in paperTopic.topic.answer"
            :key="answer.id"
          >
            <img
              :src="
                isAnswerSelected(paperTopic, answer.id)
                  ? activeRadioIcon
                  : inactiveRadioIcon
              "
              alt=""
              class="check_img"
            />
            <span>{{ answer.name }}</span>
          </div>

          <!-- 多选题 -->
          <div
            v-if="paperTopic.topic.type === 2"
            class="answer_item"
            v-for="answer in paperTopic.topic.answer"
            :key="answer.id"
          >
            <img
              :src="
                isAnswerSelected(paperTopic, answer.id)
                  ? activeCheckboxIcon
                  : inactiveCCheckboxIcon
              "
              alt=""
              class="check_img"
            />
            <span>{{ answer.name }}</span>
          </div>

          <!-- 填空题 -->
          <!-- <div v-if="paperTopic.topic.type === 3" class="answer_item">
            <div class="user-answers">
              <div
                class="answer-line"
                v-for="(answer, idx) in paperTopic.topic.question_answer
                  .answer || []"
                :key="idx"
              ></div>
            </div>
          </div> -->

          <!-- 判断题 -->
          <div
            v-if="paperTopic.topic.type === 4"
            class="answer_item"
            v-for="answer in paperTopic.topic.answer"
            :key="answer.id"
          >
            <img
              :src="
                isAnswerSelected(paperTopic, answer.id)
                  ? activeRadioIcon
                  : inactiveRadioIcon
              "
              alt=""
              class="check_img"
            />
            <span>{{ answer.name }}</span>
          </div>

          <!-- 简答题 -->
          <div v-if="paperTopic.topic.type === 5" class="short_answer">
            {{ paperTopic.topic.question_answer.answer || "无回答" }}
          </div>
        </div>

        <!-- 正确答案 -->
        <div
          class="right_answers dis_flex just_space_between"
          v-if="paperTopic.topic.type !== 3"
        >
          <div class="answers_option">
            {{ paperTopic.topic.type === 5 ? "本题得分：" : "正确答案：" }}
            <span
              v-if="paperTopic.topic.type === 1 || paperTopic.topic.type === 4"
            >
              {{ getCorrectAnswerName(paperTopic) }}
            </span>
            <span v-if="paperTopic.topic.type === 2">
              {{ getCorrectAnswerNames(paperTopic).join("、") }}
            </span>
            <!-- <span v-if="paperTopic.topic.type === 3">
              yyyy
              {{ getFillBlankAnswers(paperTopic).join("、") }}
            </span> -->
            <template v-if="paperTopic.topic.type === 3"> </template>
          </div>
          <div class="answers_score">
            {{
              paperTopic.topic.question_answer.score === 0
                ? "× 0分"
                : `√ ${paperTopic.topic.question_answer.score}分`
            }}
          </div>
        </div>
        <div v-else class="mar_top32">
          <div
            v-for="(userAnswer, idx) in paperTopic.topic.question_answer
              .answer || []"
            :key="idx"
          >
            <div>
              <div class="user_answer">{{ idx + 1 }} {{ userAnswer }}</div>
              <div class="right_answers dis_flex just_space_between mar_top8">
                <div class="answers_option">
                  正确答案：{{ getFillBlankAnswers(paperTopic)[idx] || "无" }}
                </div>
                <div class="answers_score">
                  {{ getBlankScore(paperTopic, idx) }}分
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 简答题参考答案 -->
        <div v-if="paperTopic.topic.type === 5" class="mar_top8">
          <div class="reference_tit mar_top8">参考答案：</div>
          <div class="reference_txt mar_top8">
            {{ paperTopic.topic.answer[0]?.name }}
          </div>
        </div>
      </div>
    </div>

    <div v-if="info.is_comment == 1">
      <div class="inner_title padding_aside_694 margin_1">
        <img class="deraction_img" src="@/assets/images/common/bar.png" alt />
        <div>管理员点评</div>
      </div>
      <div class="comment_box">
        <div class="comment_txt">{{ info.comment }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { convertTimestampToDateTime } from "@/utils/time";
import { checkResult, delQnSingleReport } from "@/api/evaluation/questionnaire";
export default {
  data() {
    return {
      resultId: "",
      info: {},
      activeRadioIcon: require("@/assets/images/common/radio1.png"),
      inactiveRadioIcon: require("@/assets/images/common/radio11.png"),
      activeCheckboxIcon: require("@/assets/images/common/checkbox11.png"),
      inactiveCCheckboxIcon: require("@/assets/images/common/checkbox1.png"),
    };
  },
  computed: {
    getStudentStatus() {
      return (status) => {
        switch (status) {
          case 0:
            return "不限";
          case 1:
            return "在读";
          case 2:
            return "已毕业";
          case 3:
            return "已退学";
          default:
            return "";
        }
      };
    },
  },
  created() {
    this.resultId = this.$route.query.resultId;
    this.getResult();
  },
  methods: {
    convertTimestampToDateTime,
    checkResult() {
      this.$router.push({ path: "/questionnaireResult" });
    },
    async getResult(id) {
      let res = await checkResult({ id: this.resultId });
      if (res.code == 200) {
        this.info = res.data;
      }
    },
    getBlankScore(paperTopic, index) {
      // 计算单个填空的分值（总分 ÷ 填空数量）
      const totalScore = parseFloat(paperTopic.topic.score) || 0;
      const blankCount = paperTopic.topic.answer.length || 1;
      const singleScore = totalScore / blankCount;

      // 判断该填空是否正确
      const userAnswers = paperTopic.topic.question_answer.answer || [];
      const correctAnswers = this.getFillBlankAnswers(paperTopic);
      const isCorrect = userAnswers[index] === correctAnswers[index];

      // 返回实际得分（正确得满分，错误得0分）
      return isCorrect ? "√ " + singleScore.toFixed(1) : "×  " + 0;
    },

    // 获取填空题的正确答案（保持不变）
    getFillBlankAnswers(paperTopic) {
      return paperTopic.topic.answer
        .sort((a, b) => a.num - b.num)
        .map((answer) => answer.name);
    },

    // 获取题目类型名称
    getQuestionTypeName(type) {
      switch (type) {
        case 1:
          return "单选题";
        case 2:
          return "多选题";
        case 3:
          return "填空题";
        case 4:
          return "判断题";
        case 5:
          return "简答题";
        default:
          return "未知类型";
      }
    },

    // 判断答案是否被选中
    isAnswerSelected(paperTopic, answerId) {
      const userAnswer = paperTopic.topic.question_answer.answer;

      if (paperTopic.topic.type === 1 || paperTopic.topic.type === 4) {
        // 单选题和判断题
        return userAnswer === answerId.toString();
      } else if (paperTopic.topic.type === 2) {
        // 多选题
        return (
          Array.isArray(userAnswer) && userAnswer.includes(answerId.toString())
        );
      }

      return false;
    },

    // 获取单选题/判断题的正确答案名称
    getCorrectAnswerName(paperTopic) {
      const correctAnswer = paperTopic.topic.answer.find(
        (answer) => answer.status === 1
      );
      return correctAnswer ? correctAnswer.name : "无";
    },

    // 获取多选题的正确答案名称列表
    getCorrectAnswerNames(paperTopic) {
      return paperTopic.topic.answer
        .filter((answer) => answer.status === 1)
        .map((answer) => answer.name);
    },

    // 处理填空题内容，替换input标签
    formatFillBlankContent(paperTopic) {
      let content = paperTopic.topic.content;
      const userAnswers = paperTopic.topic.question_answer.answer || [];

      // 替换填空题中的input标签为用户答案
      userAnswers.forEach((answer, index) => {
        const inputRegex = new RegExp(
          `<input[^>]*class="index${index + 1}"[^>]*>`,
          "gi"
        );
        // 检查是否为正确答案
        const correctAnswers = this.getFillBlankAnswers(paperTopic);
        const correctAnswer = correctAnswers[index] || "";
        const isCorrect = answer === correctAnswer;

        content = content.replace(
          inputRegex,
          `
          <span class="filled-blank ${isCorrect ? "correct" : "incorrect"}">
            ${answer || "未填写"}
          </span>
        `
        );
      });

      return content;
    },
    async toDelete() {
      this.$popup({
        visible: false,
        title: "提示",
        message: "确定要删除此记录吗？",
        confirmOperate: async () => {
          let par = {
            id: this.info.task_id,
            paper_id: this.info.paper_id,
          };
          let res = await delQnSingleReport(par);
          if (res.code == 200) {
            this.$toast.success("删除成功");
            this.$router.go(-1);
          }
        },
      });
    },

    // 获取填空题的正确答案
    getFillBlankAnswers(paperTopic) {
      return paperTopic.topic.answer
        .sort((a, b) => a.num - b.num)
        .map((answer) => answer.name);
    },
  },
};
</script>

<style scoped lang="less">
/* 新增样式：填空题填充效果 */
.filled-blank {
  display: inline-block;
  min-width: 100px;
  border-bottom: 1px solid #000;
  text-align: center;
  margin: 0 5px;
  padding: 0 5px;
}

.filled-blank.correct {
  color: #27ae60; /* 正确答案颜色 */
}

.filled-blank.incorrect {
  color: #e74c3c; /* 错误答案颜色 */
  text-decoration: line-through;
}

/* 填空题答案显示 */
.user-answers {
  margin-top: 8px;
}

.answer-line {
  margin-bottom: 6px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  margin-right: 8px;
  min-width: 60px;
}

.user-answer {
  margin-right: 10px;
  font-weight: 500;
}

.correct-answer {
  color: #27ae60;
  font-size: 0.9em;
  margin-left: 10px;
}

/* 移除v-html中input的边框 */
.question_tit input {
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none;
  text-align: center;
}

/* 简答题每一行添加虚线 */
.short_answer {
  white-space: pre-wrap;
}

.short_answer > span {
  display: inline-block;
  width: 100%;
  border-bottom: 1px dashed #000000;
}
/* 新增样式：填空题填充效果 */
.filled-blank {
  display: inline-block;
  min-width: 100px;
  border-bottom: 1px solid #000;
  text-align: center;
  margin: 0 5px;
}

/* 移除v-html中input的边框 */

:deep(.question_tit input) {
  border: none;
  outline: none;
  text-align: center;
  border-bottom: 1px solid #000;
}

/* 简答题每一行添加虚线 */
.short_answer {
  white-space: pre-wrap;
}

.short_answer > span {
  display: inline-block;
  width: 100%;
  border-bottom: 1px dashed #000000;
}
.question_box {
  padding: 14px 0;
  border-bottom: 1px solid #dddddd;
  &:last-child {
    border-bottom: none;
  }
}
.short_answer {
  color: #333333;
  font-size: 14px;
  margin-top: 20px;
  border-bottom: 1px dashed #000000;
}
.type_tit,
.question_tit {
  color: #333333;
  font-size: 15.33px;
}
.question_tit {
  margin-top: 17px;
}
.answer_item {
  color: #333333;
  font-size: 14px;
  margin-top: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.check_img {
  width: 14.67px;
  height: 14.67px;
  margin-right: 14px;
  vertical-align: -4px;
}

.user_answer {
  color: #333333;
  font-size: 15px;
  padding: 5px 0;
  border-bottom: 1px dashed rgba(0, 0, 0, 0.2);
}
.right_answers {
  width: 100%;
  height: 30px;
  background: #f4f6fa;
  border-radius: 6.67px;
  margin-top: 20px;
  padding: 0 10px;
  box-sizing: border-box;
}
.answers_option {
  color: #999999;
  font-size: 14px;
}
.answers_score {
  width: 80px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  color: #ffffff;
  font-size: 13px;
  background: linear-gradient(0deg, #ffffff -20%, rgba(255, 255, 255, 0) 20%),
    #ff9500;
  border-radius: 3.67px;
}
.reference_tit {
  font-size: 14px;
  color: #555555;
}
.reference_txt {
  width: 100%;
  padding: 10px 14px;
  background: #f4f6fa;
  border-radius: 6.67px;
  color: #999999;
  font-size: 14px;
  border: 0;
  box-sizing: border-box;
}
.comment_box {
  margin: 0 10px;
  padding-bottom: 30px;
}
.comment_txt {
  background: #ffffff;
  border-radius: 6.67px;
  color: #333333;
  font-size: 15.33px;
  line-height: 30.67px;
  padding: 26px 12px;
  box-sizing: border-box;
  width: 100%;
  border: none;
}

.task_det {
  color: #333333;
  background-color: #f4f6fa;
}
.dis_flex {
  display: flex;
  align-items: center;
}
.flex1 {
  flex: 1;
}
.just_space_between {
  justify-content: space-between;
}
.mar_top8 {
  margin-top: 8px;
}
.mar_top32 {
  margin-top: 32px;
}
.block_item {
  height: fit-content;
  background: #ffffff;
  border-radius: 6.94px;
  box-sizing: border-box;
  margin: 10px;
}
.bottom_line {
  position: relative;
}
.bottom_line::before {
  display: block;
  width: 100%;
  height: 0.35px;
  background: #dddddd;
  position: absolute;
  bottom: 0;
  left: 0;
  content: "";
}
.inner_title {
  height: 24.31px;
  font-size: 15.97px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: bold;
  text-align: left;
  color: #333333;
  display: flex;
  align-items: center;
  gap: 10.42px;
  margin-bottom: 19.1px;
}
.deraction_img {
  height: 15.97px;
}
.padding_aside_694 {
  padding-left: 6.94px;
  padding-right: 6.94px;
}
.scale_topic {
  padding: 22.7425px 20.84px 15.4525px 20.84px;
  box-sizing: border-box;
  text-align: center;
}
.scale_name {
  font-size: 18px;
  line-height: 18px;
  color: #00aeff;
  font-weight: bold;
  margin-bottom: 16.33px;
}
.scale_tip {
  font-size: 15.33px;
  line-height: 15.33px;
  color: #666666;
}
.margin_1 {
  margin-top: 15.62px;
  margin-bottom: 15.27px;
}

.user_info {
  width: 340.28px;
  height: fit-content;
  background: #ffffff;
  border: 0.35px solid #cccccc;
  border-radius: 3.47px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
}
.border_right {
  border-right: 0.35px solid #cccccc;
}
.border_bottom {
  border-bottom: 0.35px solid #cccccc;
}
.width_1 {
  width: calc(76.74px - 0.35px);
}
.width_2 {
  width: calc(135.76px - 0.35px);
}
.width_3 {
  width: calc(62.5px - 0.35px);
}
.width_4 {
  width: calc(69.44px);
}
.width_5 {
  width: calc(263.19px - 0.35px * 4);
}
.width_6 {
  width: calc(104.51px - 0.35px);
}
.width_7 {
  width: calc(235.42px - 0.35px * 4);
}
.width_8 {
  width: calc(103px - 0.35px);
}
.pad_0_14 {
  padding: 0 14px;
}
.info_item {
  line-height: 24.3px;
  font-size: 12.33px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  box-sizing: border-box;
  padding: 5.21px 10.42px;
}
.info_label {
  text-align: justify;
  word-break: keep-all;
  color: #666666;
}
.info_ctt {
  color: #333333;
}
.bottom_padding_1389 {
  padding-bottom: 13.89px;
}
.item_info {
  padding: 16px 13px;
  border-radius: 6.67px;
  margin: 0 10px 10px 10px;
  background-color: #ffffff;
  &:last-child {
    margin-bottom: 0;
  }
}
.del_img {
  width: 18px;
  height: 18px;
}
</style>
